<!-- 生成审核任务页面 -->
<template>
  <div>
    <span>请选择文件</span>
    <span style="color: #ccc; font-size: 14px"> (请选择待审核的Excel文件)</span>
  </div>
  <div style="display: flex; margin-top: 40px">
    <el-input style="width: 375px" :value="taskStore.generateTask.fileName">{{
      taskStore.generateTask.fileName
    }}</el-input>

    <el-button @click="isUpload" v-show="showUpload" type="primary"
      style="margin: 0 20px; color: #fff">上传文件并生成任务</el-button>
    <el-upload v-show="!showUpload" ref="uploadRef" :limit="1" accept=".xlsx, .xls,.xlsm, .xlsb,.xltm,.xltx"
      :action="upload.url" name="fileStream" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess" :auto-upload="true" :data="{ taskType: 1 }" :headers="upload.headers">
      <!-- name ="file" 上传的文件字段名,默认就是file -->
      <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon> -->
      <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
      <!-- <template #tip>

       </template> -->
      <el-button type="primary" style="margin: 0 20px; color: #fff">上传文件</el-button>

      <!-- <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <div class="el-upload__tip">
            <span>表格导入种类：</span>
            <el-radio-group v-model="radioImport" size="small">
              <el-radio value="erp" border>ERP表</el-radio>
              <el-radio value="inventory" border>盘点物资表</el-radio>
            </el-radio-group>
          </div>
          <span>仅允许导入xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            :href =" `${currentEnv}/static/template/${radioImport=='erp'? 'ERP库存表导入模板.xlsx' :'盘点表导入模板.xlsx'} ` "
            style="font-size: 12px; vertical-align: baseline"
            >下载模板</el-link
          >
        </div>
      </template> -->
    </el-upload>
    <!-- <el-button type="primary" style="margin-left: 20px;">上传文件</el-button> -->
    <el-button type="primary" @click="downLoad">下载模板</el-button>
  </div>
  <!-- <el-divider /> -->
  <!-- <div>
    <el-button type="primary">从外部系统获取数据生成任务</el-button>
  </div> -->

  <el-dialog v-model="dialogVisible" title="登录ECP" width="500">
    <div>
      <el-input v-model="src" style="width: 100%" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
        placeholder="请将ECP登录链接粘贴到此处" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="login"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, getCurrentInstance, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import useTaskStore from '@/store/task/index'
import useLoginStore from '@/store/user/index.js'

const loginStore = useLoginStore()
const taskStore = useTaskStore()
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  params: {},

  // 设置上传的请求头部
  // headers: { Authorization: 'Bearer ' },
  headers: { token: JSON.parse(localStorage.getItem('loginInfo')!).token },
  // // 上传的地址
  url: 'http://47.117.36.70/platform/generateMainTask'
})

/**文件上传中处理 */
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  upload.isUploading = true
}
const uploadRef = ref()
const showUpload = ref(true)
const dialogVisible = ref(false)
const src = ref('')

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  upload.open = false
  upload.isUploading = false
  uploadRef.value.handleRemove(file)
  // $emits('refreshData') //通知父组件刷新数据
  console.log('file.name', file.name)
  taskStore.generateTask.fileName = file.name

  if (response.code == 200) {
    const path = response.data
    // 构建正则表达式
    // const regex = /(?<=\/home\/ftp\/).+?(?=\.)/;

    // // 使用正则表达式提取所需部分
    // const extractedPart = path.match(regex);

    // if (extractedPart) {
    // console.log("Extracted part:", extractedPart[0]);
    taskStore.generateTask.sourceFilePath = path
    // }

    ElMessage.success(response.msg)
  } else {
    ElMessage.error(response.msg)
  }
}

const generate = async () => {
  taskStore.generateTask.taskType = '1'
  const res = await taskStore.generateTaskAPI()
  if (res.code == 200) {
    taskStore.generateTask.taskType = ''
    taskStore.generateTask.fileName = ''
    taskStore.generateTask.sourceFilePath = ''
  }
}
const isUpload = () => {
  // dialogVisible.value = true
  uploadRef.value.$el.querySelector('input').click()
}
const login = async () => {
  if (!src.value) {
    ElMessage.error('请输入ECP登录链接')
    return
  }
  let param = {
    ecpTokenURL: src.value
  }
  const res = await loginStore.loginEcps(param)
  if (res.success == 1) {
    ElMessage.success(res.message)
    uploadRef.value.$el.querySelector('input').click()
  } else {
    ElMessage.success(res.message)
  }
}

const downLoad = () => {
  if (process.env.NODE_ENV == "development") {
    window.location.href = `http://47.117.36.70/platform/downloadCheckTemplate`;
  } else {
    const host = window.location.protocol + "//" + window.location.host;
    window.location.href = `${host}/platform/downloadCheckTemplate`;
  }
}
</script>
